package com.admin.utils.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;


/**
 * 获取Ip地址工具类
 *
 * @author monxz
 * @Date  2021年2月25日下午4:12:21
 * @Des
 *
 */
public class IPUtils {

	/**
	 * 获取IP地址
	 * 
	 * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
	 * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
	}
	
	/**
	 * 获取到本机的内弯Ip
	 * @return
	 * @throws SocketException
	 */
	 public static String getLocalInnetIp()  {
	       String localip = null;// 本地IP，如果没有配置外网IP则返回它
	       String netip = null;// 外网IP
	       Enumeration<NetworkInterface> netInterfaces = null;
	        try {
				netInterfaces = NetworkInterface.getNetworkInterfaces();
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	       InetAddress ip = null;
	       boolean finded = false;// 是否找到外网IP
	       while (netInterfaces.hasMoreElements() && !finded) {
	         NetworkInterface ni = netInterfaces.nextElement();
	         Enumeration<InetAddress> address = ni.getInetAddresses();
	           while (address.hasMoreElements()) {
	               ip = address.nextElement();
	             if (!ip.isSiteLocalAddress() 
	                        &&!ip.isLoopbackAddress() 
	                        &&ip.getHostAddress().indexOf(":") == -1){// 外网IP
	                   netip = ip.getHostAddress();
	                   finded = true;
	                             break;
	           } else if (ip.isSiteLocalAddress() 
	                     &&!ip.isLoopbackAddress() 
	             &&ip.getHostAddress().indexOf(":") == -1){// 内网IP
	                   localip = ip.getHostAddress();
	               }
	           }
	       }
	       if (netip != null && !"".equals(netip)) {
	           return netip;
	       } else {
	           return localip;
	       }
	   }
	 
	 
	   /**
	     * 获取本机的外网ip地址
	     *
	     * @return
	     */
	    public static String getV4IP() {
	        String ip = "";
	        String chinaz = "http://ip.chinaz.com";
	 
	        StringBuilder inputLine = new StringBuilder();
	        String read = "";
	        URL url = null;
	        HttpURLConnection urlConnection = null;
	        BufferedReader in = null;
	        try {
	            url = new URL(chinaz);
	            urlConnection = (HttpURLConnection) url.openConnection();
	            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
	            while ((read = in.readLine()) != null) {
	                inputLine.append(read + "\r\n");
	            }
	            //System.out.println(inputLine.toString());
	        } catch (MalformedURLException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            if (in != null) {
	                try {
	                    in.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
	        Matcher m = p.matcher(inputLine.toString());
	        if (m.find()) {
	            String ipstr = m.group(1);
	            ip = ipstr;
	            //System.out.println(ipstr);
	        }
	        return ip;
	    }
	 
	    public static void main(String[] args) throws SocketException {
			System.err.println(getLocalInnetIp());
		}
	

}
